package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.article.service.IPublishService;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

@Service
public class IPublishServiceImpl implements IPublishService {
    @Autowired
    private MinIOService minIOService;

    @Autowired
    private IApArticleService articleService;

    @Autowired
    private Configuration configuration;

    /**
     * 生成静态页面
     * @param article
     * @param content
     */
    @Async
    @Override
    public void createHTML(ApArticle article, String content) {
        System.out.println(Thread.currentThread().getName() + " 开始执行静态页面服务");
//           使用freemarker生成html文件
        try {
//           获取模板
            Template template = configuration.getTemplate("article.ftl");
//           准备数据
            Map<String, Object> map = new HashMap<>();
            map.put("content", JSON.parseArray(content));
//           合并模板和数据
            Writer writer = new StringWriter();
            template.process(map, writer);
//           将文件存放到minio中
            String name = article.getId() + ".html";
//           构建输入流
            InputStream is = new ByteArrayInputStream(writer.toString().getBytes());
            String url = minIOService.upload(name, is, "text/html");
//           将minio返回的地址保存到文章表中
            article.setStaticUrl(url);
            articleService.updateById(article);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
